package com.example.nextgen.util;

import cn.hutool.core.util.CharUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * 文本拆分工具
 * @author martin
 * @date Created in 2022/11/8 20:26
 * @description
 */
public class TextSplitter {

    public static final Pattern BLANK_CHAR_SPLIT = Pattern.compile("[ \\t]+?");

    public static Object split(String text,List<String> keys){
        String splitText = JSON.toJSONString(split(text));
        if (JSON.isValidObject(splitText)){
            JSONObject jsonObject = JSON.parseObject(splitText);
            for (int i = 0; i < keys.size(); i++) {
                Object value = jsonObject.remove(String.valueOf(i));
                jsonObject.put(keys.get(i),value);
            }
            return jsonObject.toJSONString();
        }else if (JSON.isValidArray(splitText)) {
            JSONArray jsonArray = JSON.parseArray(splitText);
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                for (int j = 0; j < keys.size(); j++) {
                    Object value = jsonObject.remove(String.valueOf(j));
                    jsonObject.put(keys.get(j), value);
                }
            }
            return jsonArray.toJSONString();
        }
        return null;
    }

    public static Object split(String text){
        String[] allLines = text.split(String.valueOf(CharUtil.LF));
        if (allLines.length == 0){
            return null;
        }
        int valueSize = allLines[0].split(BLANK_CHAR_SPLIT.pattern()).length;
        return Arrays.stream(allLines).map(s -> {
            Map<String, Object> map = new HashMap<>();
            String[] values = s.split(BLANK_CHAR_SPLIT.pattern());
            for (int i = 0; i < valueSize; i++) {
                map.put(String.valueOf(i), values[i]);
            }
            return map;
        }).collect(Collectors.toList());
    }

    public static Object checkGetPlainTextOrJson(String text){
        if (JSON.isValidObject(text)){
            return JSON.parseObject(text);
        }else if (JSON.isValidArray(text)){
            return JSON.parseArray(text);
        }
        return text;
    }

}
